package com.Action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import sun.misc.BASE64Decoder;
import transformFactory.OperateImage;

import com.Entity.FamiliesInfo;
import com.Entity.UsersInfo;
import com.Service.FamiliesService;
import com.Service.UserService;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class ImageAction implements ServletResponseAware {

	private int flag = 0;

	private HttpServletResponse response;// response对象

	@Autowired
	private UserService userService;
	@Autowired
	private FamiliesService familyService;

	UsersInfo userinfo = new UsersInfo();
	FamiliesInfo familyinfo = new FamiliesInfo();

	public UsersInfo getUsersinfo() {
		return userinfo;
	}

	public void setUsersinfo(UsersInfo userinfo) {
		this.userinfo = userinfo;
	}

	public FamiliesInfo getFamiliesinfo() {
		return familyinfo;
	}

	public void setFamiliesinfo(FamiliesInfo familyinfo) {
		this.familyinfo = familyinfo;
	}

	// 个人头像
	public void uploadfile() throws Exception {

		PrintWriter out = response.getWriter();

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = ServletActionContext.getRequest()
					.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}

		try {
			JSONObject jsonObject = JSONObject.fromObject(jb.toString());

			String uploadPath;
			int userid = jsonObject.getInt("userId");
			// ByteArrayInputStream is = new
			// ByteArrayInputStream(jsonObject.get("fileData").toString().getBytes());
			BASE64Decoder decoder = new BASE64Decoder();
			String imageStr = jsonObject.get("fileData").toString();
			System.out.println("imageStr:" + imageStr);
			byte[] isbyte = decoder.decodeBuffer(imageStr);
			System.out.println("isbyte:" + isbyte.toString());
			String path = ServletActionContext.getRequest().getContextPath();
			String basePath = ServletActionContext.getRequest().getScheme()
					+ "://" + ServletActionContext.getRequest().getServerName()
					+ ":" + ServletActionContext.getRequest().getServerPort()
					+ path + "/";

			uploadPath = ServletActionContext.getServletContext().getRealPath(
					"/upload");
			File dirFile = new File(uploadPath);
			// 判断当前文件夹（路径）是否存在，如果不存在则创建
			if (!dirFile.exists()) {
				// dirFile.mkdirs();
				dirFile.mkdir();
			}
			// 为文件重命名
			String realfileName = java.util.UUID.randomUUID().toString();
			realfileName += ".png";
			File toFile = new File(uploadPath, realfileName);

			// logger.info("图片存入本地的路径="+uploadPath+"\\"+fileName);
			BufferedOutputStream stream = null;
			try {
				FileOutputStream os = new FileOutputStream(toFile);
				stream = new BufferedOutputStream(os);
				stream.write(isbyte);
			} finally {
				stream.close();
			}

			String srcImagePath = uploadPath + "/" + realfileName;
			String toImagePath = uploadPath + "/" + realfileName;

			OperateImage operateimage = new OperateImage();
			operateimage.reduceImageEqualProportion(srcImagePath, toImagePath,
					1);

			// logger.info("图片存数据库的路径="+"images/clubUpload_img/"+topic.getTopicAuthorId()+fileName);
			// topic.setTopicImageUrl(basePath+"images/clubUpload_img/"+topic.getTopicAuthorId()+"/topicImg/"+fileName);

			JSONObject returnjson = new JSONObject();
			flag = 1;
			String imageurl = basePath + "upload/" + realfileName;
			/**
			 * 更新所有表中的用户头像地址
			 */
			userinfo = this.userService.getById(userid);
			userinfo.setUserImg(imageurl);
			this.userService.save(userinfo);

			returnjson.put("flag", flag);
			returnjson.put("imageurl", imageurl);
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (ParseException e) {
			// crash and burn
			throw new IOException("Error parsing JSON request string");
		}

	}

	// 家庭组头像
	public void uploadFamily() throws Exception {
		PrintWriter out = response.getWriter();

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = ServletActionContext.getRequest()
					.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}

		try {
			JSONObject jsonObject = JSONObject.fromObject(jb.toString());

			String uploadPath;
			int familyid = jsonObject.getInt("familyId");
			// ByteArrayInputStream is = new
			// ByteArrayInputStream(jsonObject.get("fileData").toString().getBytes());
			BASE64Decoder decoder = new BASE64Decoder();
			String imageStr = jsonObject.get("fileData").toString();
			System.out.println("imageStr:" + imageStr);
			byte[] isbyte = decoder.decodeBuffer(imageStr);
			System.out.println("isbyte:" + isbyte.toString());
			String path = ServletActionContext.getRequest().getContextPath();
			String basePath = ServletActionContext.getRequest().getScheme()
					+ "://" + ServletActionContext.getRequest().getServerName()
					+ ":" + ServletActionContext.getRequest().getServerPort()
					+ path + "/";

			uploadPath = ServletActionContext.getServletContext().getRealPath(
					"/upload");
			File dirFile = new File(uploadPath);
			// 判断当前文件夹（路径）是否存在，如果不存在则创建
			if (!dirFile.exists()) {
				// dirFile.mkdirs();
				dirFile.mkdir();
			}
			// 为文件重命名
			String realfileName = java.util.UUID.randomUUID().toString();
			realfileName += ".png";
			File toFile = new File(uploadPath, realfileName);

			// logger.info("图片存入本地的路径="+uploadPath+"\\"+fileName);
			BufferedOutputStream stream = null;
			try {
				FileOutputStream os = new FileOutputStream(toFile);
				stream = new BufferedOutputStream(os);
				stream.write(isbyte);
			} finally {
				stream.close();
			}

			String srcImagePath = uploadPath + "/" + realfileName;
			String toImagePath = uploadPath + "/" + realfileName;

			OperateImage operateimage = new OperateImage();
			operateimage.reduceImageEqualProportion(srcImagePath, toImagePath,
					1);

			// logger.info("图片存数据库的路径="+"images/clubUpload_img/"+topic.getTopicAuthorId()+fileName);
			// topic.setTopicImageUrl(basePath+"images/clubUpload_img/"+topic.getTopicAuthorId()+"/topicImg/"+fileName);

			JSONObject returnjson = new JSONObject();
			flag = 1;
			String imageurl = basePath + "upload/" + realfileName;
			familyinfo = this.familyService.getById(familyid);
			familyinfo.setFamilyImg(imageurl);
			this.familyService.save(familyinfo);
			returnjson.put("flag", flag);
			returnjson.put("imageurl", imageurl);
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (ParseException e) {
			// crash and burn
			throw new IOException("Error parsing JSON request string");
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		// TODO Auto-generated method stub
		this.response = response;

	}
}